/**
 * 
 */
package servlet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.SearchRecipeBean;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import project.taip.wawwe.db.Services;
import project.taip.wawwe.model.Ingredient;
import util.RecipeUtil;

/**
 * @author Andrei Iordache
 *
 */
public class SearchRecipeServlet extends HttpServlet implements RecipeServlet {

	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request,
			HttpServletResponse response) {
		processPostGetRequest(request, response);
	}
	
	public void doPost(HttpServletRequest request,
			HttpServletResponse response) {
		processPostGetRequest(request, response);
	}
	
	/* (non-Javadoc)
	 * @see servlet.RecipeServlet#processPostGetRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public void processPostGetRequest(HttpServletRequest request,
			HttpServletResponse response) {
		SearchRecipeBean bean = (SearchRecipeBean)request.
							getAttribute("instance");
                String description = bean.getDescription();
                ArrayList<Ingredient> ingredients = RecipeUtil.getIngredientsFromText(description);
                StringBuffer sB = new StringBuffer();
                ArrayList<project.taip.wawwe.model.Recipe> array =Services.searchRecipe(null, ingredients, null, null);
                if (null != array) 
            for (project.taip.wawwe.model.Recipe r : array) {
                     sB.append("<br>");
                sB.append("<b>Name: </b>");
                sB.append("<br>");
                sB.append(r.getName());
                sB.append("<br>");
                sB.append("<br>");
                sB.append("<b>Ingredients: </b>");
                sB.append("<br>");
                for (project.taip.wawwe.model.Ingredient i : r.getIngredients()) {
                    sB.append(i.getQuantity() + " " + i.getUnit() + " " + i.getName());
                    sB.append("<br>");
                }
                sB.append("<br>");
                sB.append("<b>Description: </b>");
                sB.append("<br>");
                sB.append(r.getDescription());
                sB.append("<br>");
                sB.append("<br>");
                }
             bean.setResult(sB.toString());
        try {
            getServletContext().getRequestDispatcher("/search.jsp?process=false").
                    forward(request, response);
        } catch (ServletException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
	}

}
